package com.example.book.common.utils;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 文件上传相关
 * @author hcj
 */
public class LocalFileUtils {

    private static List<String> fileTypes = new ArrayList<String>();

    // 拦截类型
    static {
        fileTypes.add(".php");
        fileTypes.add(".py");
        fileTypes.add(".bmp");
    }

    /**
     * 上传文件
     *
     * @param id
     * @param path
     * @param realPath
     * @param multipartFile
     * @return
     * @throws IOException
     */
    public static String upload(String id, String path, String realPath, MultipartFile multipartFile) throws IOException {

        String date = DateUtils.formatDate();

        realPath = realPath + File.separator + id + File.separator + date + File.separator;

        path = path + File.separator + id + File.separator + date + File.separator;

        File file1 = new File(realPath);
        if (!file1.exists()) {
            file1.mkdirs();
        }

        FileOutputStream outputStream = null;
        try {

            String originalFilename = multipartFile.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();

            if (fileTypes.contains(suffix)) {
                return null;
            }

            InputStream inputStream = multipartFile.getInputStream();
            String fileName = Constants.uuid() + suffix;
            String files = realPath + fileName;
            outputStream = new FileOutputStream(files);

            boolean res = upload(outputStream, inputStream);

            if (res) {
                // 返回的是数据路径
                return path + fileName;
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            outputStream.close();
        }
        return null;
    }

    /**
     * 浏览器文件下载方法
     *
     * @param fileName
     * @param request
     * @param response
     * @throws IOException
     */
    public static void outWriterFile(String fileName, String realFile, HttpServletRequest request, HttpServletResponse response) throws IOException {

        response.setContentType("text/html");

        FileInputStream inputStream = new FileInputStream(realFile);

        String agent = request.getHeader("USER-AGENT");
        if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GB2312"), "ISO-8859-1"));
        } else {
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        }

        OutputStream out = null;
        try {
            out = response.getOutputStream();
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) > 0) {
                out.write(bytes, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static void download(String path, String fileName, OutputStream out) throws IOException {
        String realFile = path + fileName;
        FileInputStream fileInputStream = new FileInputStream(realFile);
        try {
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) > 0) {
                out.write(bytes, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.flush();
            out.close();
        }

    }

    private static boolean upload(FileOutputStream fileOutputStream, InputStream inputStream) throws IOException {
        boolean b = false;
        try {
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) > 0) {
                fileOutputStream.write(bytes, 0, len);
            }
            b = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            fileOutputStream.close();
            inputStream.close();
        }
        return b;
    }

    /**
     * 邮件发送后删除附件信息
     *
     * @param files
     */
    public static void delete(List<File> files, File file1) {
        if (file1 == null) {
            for (File file : files) {
                if (file.exists()) {
                    file.delete();
                }
            }
        } else {
            file1.delete();
        }
    }

}
